package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.StoreInoutDetailLogic;
import cn.topevery.garden.dal.logic.StoreInoutLogic;
import cn.topevery.garden.dal.logic.StroeInoutFileLogic;
import cn.topevery.garden.entity.impot.StoreInoutImportParam;
import cn.topevery.garden.entity.po.StoreInout;
import cn.topevery.garden.entity.po.StoreInoutDetail;
import cn.topevery.garden.entity.po.StroeInoutFile;
import cn.topevery.garden.entity.query.StoreInoutDetailQuery;
import cn.topevery.garden.entity.query.StoreInoutQuery;
import cn.topevery.garden.entity.vo.StoreInoutVO;
import cn.topevery.garden.wapi.utils.ExcelUtils;
import cn.topevery.garden.wapi.utils.StatusUtils;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  入库、出库管理
 *
 * @author code-generate
 * @date 2021-08-30
 */
@Api(tags = "入库、出库接口")
@RestController
@RequestMapping("/storeInout")
public class StoreInoutController extends BaseController {

    @Autowired
    private Mapper mapper;

    @Autowired
    StoreInoutLogic storeInoutLogic;

    @Autowired
    StoreInoutDetailLogic storeInoutDetailLogic;

    @Autowired
    StroeInoutFileLogic stroeInoutFileLogic;


    /**
     * 获取分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<StoreInout>> listPage(@RequestBody StoreInoutQuery query) {
        DataPager<StoreInout> list = storeInoutLogic.listPage(query);

        StoreInoutDetailQuery query2 = new StoreInoutDetailQuery();
        query2.pageSize = 1000;
        query2.pageIndex = 1;
        for(StoreInout storeInout : list.records){
            query2.setPId(storeInout.getId());
            DataPager<StoreInoutDetail> pageList = storeInoutDetailLogic.listPage(query2);
            storeInout.setStoreInoutDetailList(pageList.records);

            // 获取附件
            List<StroeInoutFile> fileList = stroeInoutFileLogic.getListByPid(storeInout.getId());
            storeInout.setFileList(fileList);
        }

        return JsonResult.ok(list);
    }

    @ApiOperation(value = "获取物品详情列表")
    @PostMapping("/getDetailList")
    public JsonResult<DataPager<StoreInoutDetail>> getDetailList(@RequestBody StoreInoutDetailQuery query) {
        return JsonResult.ok(storeInoutDetailLogic.listPage(query));
    }

    @ApiOperation("新增/编辑 信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(@Valid @RequestBody StoreInout dto) {
        // 出库时进行库存校验
        if(dto.getStoreType() == 2){
            Map temp = storeInoutDetailLogic.checkNum(dto.getStoreInoutDetailList());
            if(!(Boolean) temp.get("status")){
                return JsonResult.error(String.valueOf(temp.get("msg")));
            }
        }

        boolean isSavwe = storeInoutLogic.saveOrUpdate(getUser().id.toString(),dto);
        if(isSavwe){
            // 保存详情
            storeInoutDetailLogic.saveOrUpdate(getUser().id.toString(), dto.getId(),dto.getStoreType(), dto.getStoreInoutDetailList());

            // 保存附件
            stroeInoutFileLogic.saveOrUpdate(getUser().id.toString(), dto.getId(), dto.getFileList());
        }
        return JsonResult.ok();
    }

    @ApiOperation("通过Id获取详情")
    @GetMapping("/getInfoById")
    public JsonResult getInfoById(@RequestParam Integer id) {
        StoreInout storeInout = storeInoutLogic.getEntity(id);

        // 获取详情列表
        StoreInoutDetailQuery query = new StoreInoutDetailQuery();
        query.pageSize = 1000;
        query.pageIndex = 1;
        query.setPId(id);
        DataPager<StoreInoutDetail> pageList = storeInoutDetailLogic.listPage(query);
        storeInout.setStoreInoutDetailList(pageList.records);

        // 获取附件
        List<StroeInoutFile> fileList = stroeInoutFileLogic.getListByPid(id);
        storeInout.setFileList(fileList);

        return JsonResult.ok(storeInout);
    }

    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        storeInoutLogic.deleteBatchById(getUser().id.toString(),ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(StoreInoutQuery query, HttpServletResponse response) {
        List<StoreInout> list = storeInoutLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", StoreInout.class, "", response);
    }

    /**
     * 描述 检查导入数据.
     *
     * @param file the file
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:59 Analysis excel data json result.
     */
    @PostMapping("/analysisExcel")
    public JsonResult AnalysisExcelData(@RequestParam("file") MultipartFile file) {
        boolean isPass = true;
        String msg = "";
        List<StoreInoutVO> list = null;
        try {
            list = ExcelUtils.importExcel(file, 0, 1, StoreInoutVO.class);
        } catch (Exception e) {
            msg = "解析发生错误，请按照模板格式填写数据！";
            return JsonResult.error(msg);
        }

        List<StoreInoutVO> newData = new ArrayList<>();
        for (StoreInoutVO p : list) {
            String anaylsisRes = "";
            if (p.getSid() == 0 && p.getBillCode() == null) {
                break;
            }
            boolean isExists1 = storeInoutLogic.isExit("c_bill_code", p.getBillCode());
            if (isExists1) {
                anaylsisRes += "单据编号已存在；";
            }

            if (anaylsisRes.length() > 0) {
                p.setPass(false);
                p.setAnalysisRes(anaylsisRes);
            } else {
                p.setPass(true);
                p.setAnalysisRes("验证通过");
            }
            newData.add(p);
        }
        isPass = !newData.stream().anyMatch(a -> a.isPass() == false);
        Map<String, Object> res = new HashMap<>();
        res.put("isPass", isPass);
        res.put("data", newData);
        return JsonResult.ok(res);
    }

    /**
     * 描述 导入数据.
     *
     * @param param the param
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:53 Import excel data json result.
     */
    @PostMapping("/importExcel")
    public JsonResult importExcelData(@RequestBody StoreInoutImportParam param) {

        SysUser user = getUser();
        if (param.getTableData() != null && param.getTableData().size() > 0) {

            for (StoreInoutVO p : param.getTableData()) {
                StoreInout tmp = new StoreInout();

                tmp.setBillCode(p.getBillCode());
                tmp.setBillDate(p.getBillDate());
                tmp.setSupplier(p.getSupplier());
                tmp.setType(String.valueOf(StatusUtils.getGoodsType(p.getType())));
                tmp.setStoreType(param.getType());
                tmp.setRecordUserName(p.getRecordUserName());
                tmp.setRecordDate(p.getRecordDate());
                tmp.setClaimUser(p.getClaimUser());

                storeInoutLogic.saveOrUpdate(user.id.toString(),tmp);
            }
        } else {
            return JsonResult.error("导入数据列表不能为空");
        }
        return JsonResult.ok();
    }
}
